import User from '@/class/user/user.js'

import commonMixin from '@/mixins/common.js'

export default {
  name: 'bindMobile',
  mixins: [
    commonMixin
  ],
  data () {
    return {
      user: new User(),
      
      form: {
        mobile: '',
        verifyNum: '',
        password: '',
        comfirmPwd: ''
      },
      // 校验结果
      validate: {
        mobile: false,
        verifyNum: false,
        password: false,
        comfirmPwd: false
      },
      validateTxt: {
        mobile: '',
        verifyNum: '',
        password: '',
        comfirmPwd: ''
      },
      
      // 短信发送间隔
      smsColdTimeLeft: 0
    }
  },
  computed: {
    // 用户是否首次绑定手机
    isFirstBind () {
      return this.user.mobile === ''
    },
    
    // 短信按钮文字
    smsButtonText () {
      if (this.smsColdTimeLeft === 0) {
        return '获取验证码'
      }
      return '等待' + this.smsColdTimeLeft + '秒'
    }
  },
  mounted () {
    // 设置短信发送间隔
    this.initSmsCold()
    // 设置校验器
    this.setValidate()
  },
  methods: {
    // 设置校验器
    setValidate () {
      // 验证码校验器
      this.$refs.verifyNumValidator.setValidate((num) => {
        if (num.length !== 6 || !this.$u.str.isNumberString(num) || num.indexOf('.') >= 0) {
          return false
        }
        return true
      })
      
      if (this.isFirstBind) {
        // 首次绑定手机需要设置密码
        // 密码校验器
        this.$refs.passwordValidator.setValidate((pwd) => {
          this.$refs.confirmValidator.doValidate()
          if (pwd.length < 6) {
            return { sign: false, txt: '密码长度不得少于6位' }
          }
          return true
        })
        
        // 重复密码校验器
        this.$refs.confirmValidator.setValidate((pwd) => {
          if (pwd !== this.form.password) {
            return { sign: false, txt: '两次输入的密码不相同' }
          }
          if (pwd.length < 6) {
            return { sign: false, txt: '密码长度不得少于6位' }
          }
          return true
        })        
      }
      else {
        // 否则不需要。直接通过密码验证
        this.validate.password = true
        this.validate.comfirmPwd = true
      }
    },
    
    // 校验器检验
    checkValidate () {
      let res = true
      let errorKey = ''
      for (let key in this.validate) {
        res = res & this.validate[key]
        if (!res) {
          errorKey = key
          break
        }
      }
      if (!res) {
        this.$u.msg.toast(this.validateTxt[errorKey])
        return false
      }
      return true
    },
    
    // 绑定手机号
    async bind () {
      await this.user.userCloudAuth()
    },
    
    // 设置短信发送间隔
    setSmsCold (coldTime) {
      const nowTime = new Date().getTime()
      const endTime = nowTime + coldTime * 1000
      // 保存入缓存
      uni.setStorageSync('smsColdTime', endTime)
      
      this.smsColdTimeLeft = coldTime
      // 设置计时器，每秒时间减一
      this.interval(1000, 'smsInterval', () => {
        this.smsColdTimeLeft--
        if (this.smsColdTimeLeft === 0) {
          // 清除定时器
          this.clearTimer('smsInterval')
        }
      })
    },
    
    // 初始化短信发送间隔
    initSmsCold () {
      // 读取缓存
      let endTime = uni.getStorageSync('smsColdTime')
      if (!this.$u.str.isNumberString(endTime)) {
        return
      }
      endTime = parseInt(endTime)
      const nowTime = new Date().getTime()
      if (nowTime >= endTime) {
        this.smsColdTimeLeft = 0
        return
      }
      
      const delta = Math.ceil((endTime - nowTime) / 1000)
      this.setSmsCold(delta)
    },
    
    // 发送短信的回调
    smsHandler () {
      if (!this.validate.mobile) {
        this.$u.msg.toast(this.validateTxt.mobile)
        return
      }
      
      this.$u.msg.loading('发送中')
      User.userCloud('user-center', 'sendSmsCode', {
        mobile: this.form.mobile,
        code: this.$u.str.randomNumStr(6),
        type: 'bind'
      })
      .then((res) => {
        console.log('绑定手机成功', res)
        
        // 设置短信发送间隔
        this.setSmsCold(this.$u.config.sys.smsColdTime)
        this.$u.msg.hideLoading()
        this.$u.msg.toast('已成功发送短信')
      })
      .catch((e) => {
        console.log('发送失败', e)
        this.$u.msg.hideLoading()
        this.$u.msg.errToast(e)
      })
    },
    
    // 确认绑定的回调
    bindHandler () {
      if (!this.checkValidate()) {
        return
      }
      
      const data = {
        mobile: this.form.mobile,
        code: this.form.verifyNum,
        password: this.form.password
      }
      this.$u.msg.loading('绑定中')
      this.user.bindMobile(data).then(() => {
        this.$u.msg.hideLoading()
        this.$u.msg.toast('绑定手机成功')
        uni.navigateBack({ delta: 1 })
      })
      .catch((e) => {
        console.log('绑定失败', e)
        this.$u.msg.hideLoading()
        this.$u.msg.errToast(e)
      })
    },
    
    // 校验输入的回调
    validateHandler (key, res, resTxt) {
      this.validate[key] = res
      this.validateTxt[key] = resTxt
    }
  }
}